//
//  LVSessionReportReasonPopView.m
//  LEVE
//
//  Created by 上官惠阳 on 2017/3/13.
//  Copyright © 2017年 dashuju. All rights reserved.
//

#import "LVSessionReportReasonPopView.h"
#import "FXBlurView.h"
#import "HYAnimationManager.h"
#import "NSString+Size.h"
#import "UIImage+Addition.h"
#import "UIView+Layer.h"

#define kTag 555555
@interface LVReportReasonCell : UITableViewCell
@property (strong,nonatomic) UIButton *seletedBtn;
@property (strong,nonatomic) UILabel *reasonLabel;

+ (CGFloat)heightOfCellWithReason:(NSString *)reason;
@end
@implementation LVReportReasonCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

        self.selectionStyle = UITableViewCellSelectionStyleNone;

        _seletedBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_seletedBtn setImage:[UIImage imageNamed:@"im_popup_not_selected"] forState:UIControlStateNormal];
        [_seletedBtn setImage:[UIImage imageNamed:@"im_popup_selected"] forState:UIControlStateSelected];
        _seletedBtn.userInteractionEnabled = NO;
        [self.contentView addSubview:_seletedBtn];

        _reasonLabel = [[UILabel alloc] init];
        _reasonLabel.textAlignment = NSTextAlignmentLeft;
        _reasonLabel.font = [UIFont systemFontOfSize:14];
        _reasonLabel.textColor = KGrayColor;
        _reasonLabel.numberOfLines = 0;
        [self.contentView addSubview:_reasonLabel];
    }
    return self;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    _seletedBtn.left = 10;
    _seletedBtn.width = 40;
    _seletedBtn.top = 0;
    _seletedBtn.height = self.height;

    _reasonLabel.left = _seletedBtn.right;
    _reasonLabel.height = 20;
    _reasonLabel.width = self.width - 60;
    _reasonLabel.centerY = _seletedBtn.centerY;
}
+ (CGFloat)heightOfCellWithReason:(NSString *)reason
{
    CGFloat height = [reason heightWithFont:[UIFont systemFontOfSize:14] constrainedToWidth:kScreenWidth - 80 - 60];

    return height + 20;
}
@end

@interface LVSessionReportReasonPopView ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>
@property (nonatomic, strong) FXBlurView *blurView;
@property (nonatomic, strong) UIView *dimmingView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, weak) UILabel *contentLabel;
@property (nonatomic, weak) UIButton *cancelBtn;
@property (nonatomic, weak) UIButton *sureBtn;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *otherReasonView;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UILabel *textAlert;

@property (nonatomic, strong) NSMutableArray *reportReasonArr;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *cancel;
@property (nonatomic, copy) NSString *sure;
@property (nonatomic, copy) BOOL(^touchBlock)(NSString *str);
@property (nonatomic, copy) BOOL(^cancelBlock)();

@property (nonatomic, strong)NSString *seletedReportReason;
@end

@implementation LVSessionReportReasonPopView
+ (BOOL)alertIsShowingInView:(UIView *)view {
    if (view == nil) view = [UIApplication sharedApplication].keyWindow;
    UIView *alert = [view viewWithTag:kTag];
    return alert != nil;
}

- (instancetype)initWithTitle:(NSString *)title cancel:(NSString *)cancel sure:(NSString *)sure reportReasons:(NSString *)reportReason,...NS_REQUIRES_NIL_TERMINATION{
    if (self = [super init]) {
        _title = title;
        _cancel = cancel;
        _sure = sure;

        NSString *str;
        va_list argumentList;
        if(reportReason) {
            [self.reportReasonArr addObject:reportReason];
            va_start(argumentList, reportReason);
            while((str = va_arg(argumentList, id))) {
                NSString *tit = [str copy];
                [self.reportReasonArr addObject:tit];
            }
            va_end(argumentList);
        }

        [self setup];
    }
    return self;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4f];

    _blurView = [[FXBlurView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    _blurView.tintColor = [UIColor clearColor];

    UILabel *contentLabel = [[UILabel alloc] init];
    [self.contentView addSubview:contentLabel];
    contentLabel.font = kFont(kScreenWidth > 320 ? 15 : 14);
    contentLabel.text = self.title;
    contentLabel.textAlignment = NSTextAlignmentCenter;
    contentLabel.textColor = kCommonBlackColor;
    contentLabel.numberOfLines = 0;
    _contentLabel = contentLabel;

    [self.tableView reloadData];

    self.otherReasonView.hidden = YES;

    UIButton *cancel = [[UIButton alloc] init];
    [cancel setTitle:self.cancel.length ? self.cancel : @"取消" forState:UIControlStateNormal];
    cancel.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [cancel addTarget:self action:@selector(cancelTouch) forControlEvents:UIControlEventTouchUpInside];
    [cancel setTitleColor:KGrayColor forState:UIControlStateNormal];

    [self.contentView addSubview:cancel];
    _cancelBtn = cancel;

    UIButton *sure = [[UIButton alloc] init];
    [ sure setTitle:self.sure.length ? self.sure : @"确定" forState:UIControlStateNormal];
    sure.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [sure addTarget:self action:@selector(sureTouch) forControlEvents:UIControlEventTouchUpInside];
    [sure setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sure.backgroundColor = KMainColor;

    [self.contentView addSubview:sure];
    _sureBtn = sure;

    [self addSubview:_contentView];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    if (self.otherReasonView.hidden) {
        [self.contentView setFrame:CGRectMake(0, 0, kScreenWidth - 80, self.reportReasonArr.count * 40 + 120)];
    }else{
        [self.contentView setFrame:CGRectMake(0, 0, kScreenWidth - 80, kScreenWidth > 320 ? 310 : 270)];
    }

    self.contentLabel.frame = CGRectMake(20, 20, self.contentView.width - 40, 25);

    self.tableView.frame = CGRectMake(0, self.contentLabel.bottom, self.contentView.width , self.reportReasonArr.count * 40);

    self.otherReasonView.frame = CGRectMake(15, self.contentLabel.bottom + 10, self.contentView.width - 30, kScreenWidth > 320 ? 155 : 115);
    self.textView.frame = CGRectMake(5, 0, self.otherReasonView.width - 10, self.otherReasonView.height);
    self.textAlert.frame = CGRectMake(10, 5, self.otherReasonView.width - 20, 20);


    if (self.cancel.length == 0 && self.sure.length != 0) {

        self.sureBtn.frame = CGRectMake(40, self.contentView.bottom - 20, self.contentView.width - 80, 40);
        [self.sureBtn makeRoundedCorners];

        [self.cancelBtn removeFromSuperview];
    } else if (self.cancel.length != 0 && self.sure.length == 0) {

        self.cancelBtn.frame = CGRectMake(40, self.contentView.bottom - 20, self.contentView.width - 80, 50);

        [self.sureBtn removeFromSuperview];

    } else if (self.cancel.length != 0 && self.sure.length != 0) {
        self.sureBtn.frame = CGRectMake(40, self.contentView.bottom - 80, self.contentView.width - 80, 40);
        [self.sureBtn makeRoundedCorners];
        self.cancelBtn.frame = CGRectMake(40, self.sureBtn.bottom, self.contentView.width - 80, 40);
    }
    self.contentView.center = self.center;
}
// 取消
- (void)cancelTouch {
    if (!self.cancelBlock) {
        [self dismissFromSuperview];
    } else {
        [UIView animateWithDuration:0.35 animations:^{
            self.alpha = 0;
        } completion:^(BOOL finished) {
            if (finished) {
                [self removeFromSuperview];
                [_blurView clearImage];
                [_blurView removeFromSuperview];
                if (self.cancelBlock) {
                    self.cancelBlock();
                }
            }
        }];
    }

}

// 确定
- (void)sureTouch {
    if (self.touchBlock) {
        [UIView animateWithDuration:0.35 animations:^{
            self.alpha = 0;
        } completion:^(BOOL finished) {
            if (finished) {
                [self removeFromSuperview];
                [_blurView clearImage];
                [_blurView removeFromSuperview];
                if (self.touchBlock) {
                    if ([_seletedReportReason isEqualToString:[self.reportReasonArr lastObject]]) {
                        _seletedReportReason = self.textView.text;
                    }
                    self.touchBlock(_seletedReportReason);
                }
            }
        }];
    } else {
        [UIView animateWithDuration:0.35 animations:^{
            self.alpha = 0;
        } completion:^(BOOL finished) {
            if (finished) {
                [self removeFromSuperview];
                [_blurView clearImage];
                [_blurView removeFromSuperview];
            }
        }];
    }
}

- (void)setupCancelBlock:(BOOL (^)())cancelBlock {
    _cancelBlock = cancelBlock;
}

- (void)setupSureBlock:(BOOL (^)(NSString *str))touchBlock {
    _touchBlock = touchBlock;
}
#pragma mark UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
    self.textAlert.hidden = textView.text.length;
}
#pragma mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.reportReasonArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LVReportReasonCell *popCell = [tableView dequeueReusableCellWithIdentifier:@"LVReportReasonCell"];
    if (!popCell) {
        popCell = [[LVReportReasonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"LVReportReasonCell"];
    }
    NSString *title = self.reportReasonArr[indexPath.row];
    popCell.reasonLabel.text = title;
    if (_seletedReportReason && [title isEqualToString:_seletedReportReason]) {
        popCell.seletedBtn.selected = YES;
    }else{
        popCell.seletedBtn.selected = NO;
    }
    return popCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = self.reportReasonArr[indexPath.row];

    return [LVReportReasonCell heightOfCellWithReason:title];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = self.reportReasonArr[indexPath.row];
    _seletedReportReason = title;

    [self.tableView reloadData];

    if (indexPath.row == self.reportReasonArr.count - 1) {
        self.otherReasonView.hidden = NO;
        self.tableView.hidden = YES;

        [self layoutSubviews];
    }else{
        self.otherReasonView.hidden = YES;
        self.tableView.hidden = NO;
    }
}
#pragma mark 懒加载
- (UIView *)contentView {
    if (_contentView == nil) {
        UIView *contentView = [[UIView alloc] init];
        [self addSubview:contentView];
        _contentView = contentView;
        contentView.layer.cornerRadius = 13.f;
        contentView.backgroundColor = [UIColor whiteColor];
    }
    return _contentView;
}
- (UITableView *)tableView {
    if(!_tableView) {
        UITableView *tab = [[UITableView alloc] init];
        tab.delegate = self;
        tab.dataSource = self;
        tab.backgroundColor = [UIColor clearColor];
        tab.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.contentView addSubview:tab];
        tab.scrollEnabled = NO;
        _tableView = tab;
    }
    return _tableView;
}
- (NSMutableArray *)reportReasonArr {
    if(!_reportReasonArr) {
        _reportReasonArr = [[NSMutableArray alloc] init];
    }
    return _reportReasonArr;
}
- (UIView *)otherReasonView
{
    if (!_otherReasonView) {
        _otherReasonView = [[UIView alloc] init];
        _otherReasonView.backgroundColor = KLightGrayColor;
        [_otherReasonView makeRoundedCornersRadius:5];
        [self.contentView addSubview:_otherReasonView];

        _textView = [[UITextView alloc] init];
        _textView.delegate = self;
        _textView.backgroundColor = [UIColor clearColor];
        _textView.font = [UIFont systemFontOfSize:14];
        [_otherReasonView addSubview:_textView];

        _textAlert = [[UILabel alloc] init];
        _textAlert.backgroundColor = [UIColor clearColor];
        _textAlert.textColor = KGrayColor;
        _textAlert.font = [UIFont systemFontOfSize:14];
        _textAlert.text = @"请输入举报原因";
        [_otherReasonView addSubview:_textAlert];
    }

    return _otherReasonView;
}
#pragma mark show/remove
- (void)showInView:(UIView *)view {

    BOOL isShowing = [LVSessionReportReasonPopView alertIsShowingInView:view];
    if (isShowing) return ;

    UIView *content = view ? view  : [UIApplication sharedApplication].keyWindow;
    _blurView.blurRadius = 0;
    self.frame = content.bounds;
    self.alpha = 0;
    self.tag = kTag;

    [content addSubview:_blurView];
    [content addSubview:self];

    [HYAnimationManager addTransformAnimationForView:self.contentView];

    [UIView animateWithDuration:0.35 animations:^{
        self.alpha = 1;
        _blurView.blurRadius = 12.0f;
    } completion:^(BOOL finished) {
        _blurView.dynamic = NO;
        [FXBlurView setUpdatesDisabled];
    }];
}
//移除掉
- (void)dismissFromSuperview
{
    [UIView animateWithDuration:0.35 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        if (finished) {
            [self removeFromSuperview];
            [_blurView clearImage];
            [_blurView removeFromSuperview];
        }
    }];
}
@end
